<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>优惠券管理</el-breadcrumb-item>
      <el-breadcrumb-item>优惠券查询</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索区 -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        :model="queryInfo.query"
        size="mini"
      >
        <el-form-item label="优惠券名称【ID】" prop="class_id">
          <el-select
            v-model="queryInfo.query.class_id"
            placeholder="请选择"
            filterable
            size="mini"
            clearable
          >
            <el-option
              v-for="item in class_arr"
              :key="item.id"
              :label="item.name + '【' + item.id + '】'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡类型" prop="product_id">
          <el-select
            v-model="queryInfo.query.product_id"
            placeholder="请选择"
            filterable
            size="mini"
            clearable
          >
            <el-option key="1" label="专用券" value="1"> </el-option>
            <el-option key="2" label="通用券" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="type">
          <el-select
            v-model="queryInfo.query.type"
            placeholder="请选择"
            filterable
            size="mini"
            clearable
          >
            <el-option key="-1" label="待生效" value="-1"> </el-option>
            <el-option key="0" label="未使用" value="0"> </el-option>
            <el-option key="1" label="已使用" value="1"> </el-option>
            <el-option key="2" label="已失效" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryInfo.query.keywords"
            placeholder="请输入券号"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="theme-background-color"
            size="mini"
            @click="searchList"
          >
            搜索
          </el-button>
          <el-button size="mini" @click="resetSearchForm"> 重置 </el-button>
        </el-form-item>
      </el-form>

      <!-- 操作区域 -->
      <div>
        <el-button
          icon="el-icon-download"
          size="mini"
          :loading="btnLoading"
          @click="downloadExcel"
        >
          导出数据
        </el-button>
      </div>

      <!-- 列表区域 -->
      <el-table :data="list" border stripe>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column
          label="券号"
          prop="coupon"
          min-width="100px"
        ></el-table-column>
        <el-table-column
          label="优惠券名称【ID】"
          min-width="150px"
          max-width="250px"
        >
          <template slot-scope="scope">
            {{ scope.row.coupon_name + '【' + scope.row.config_id + '】' }}
          </template>
        </el-table-column>
        <el-table-column label="面值 | 折扣" prop="amount"></el-table-column>
        <el-table-column label="发放时间" prop="create_time"></el-table-column>
        <el-table-column label="状态" prop="status.name"></el-table-column>
        <el-table-column label="生效日期" prop="start_date"></el-table-column>
        <el-table-column label="失效日期" prop="end_date"></el-table-column>
        <el-table-column label="操作" width="100px">
          <template slot-scope="scope">
            <el-link type="primary" @click="delayDialogVisibles(scope.row)"  v-if="scope.row.status.id != 1">
              延期 </el-link
            >&nbsp;
            <el-link type="danger" @click="removeProductById(scope.row)" v-if="scope.row.status.id != 1"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 延期操作对话框 -->
    <el-dialog
      title="延期"
      :visible.sync="delayDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <!-- 弹框内容 -->
      <el-form style="margin: 10px">
        <el-form-item label="生效日期" prp="deferDate.value4">
          <el-date-picker
            v-model="deferDate.value4"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            :disabled = disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="失效日期">
          <el-date-picker
            v-model="deferDate.value1"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            :disabled = disabledT
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="theme-background-color" @click="deferCoupon()">
          保存
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: {
          class_id: '',
          product_id: '',
          type: '',
          keywords: '',
          record_id: ''
        },
        pagenum: 1,
        pagesize: 20
      },
      list: [],
      total: 0,
      class_arr: [],
      allProducts: {},
      // 延期操作对话框的显示与隐藏
      delayDialogVisible: false,
      deferDate: {
        value4: '',
        value1: '',
        couponId: ''
      },
      btnLoading: false,
      disabled: true,
      disabledT: true
    }
  },
  created() {
    this.initData()
    this.getSelectData()
    this.getListData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('admin/Data/find', {
        code: 'coupon'
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.class_arr = res.data.coupon
    },
    searchList() {
      this.queryInfo.pagenum = 1
      this.getListData()
    },
    resetSearchForm() {
      //   console.log(this)
      this.$refs.searchFormRef.resetFields()
      this.getListData()
    },
    async getListData() {
      // 返回数据重命名为res
      this.queryInfo.query.record_id = this.$route.query.record_id // 从路由上获取参数
      const { data: res } = await this.$http.post(
        'admin/Coupon/couponList',
        this.queryInfo
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.list = res.data.list
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getListData()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getListData()
    },
    // 打开延期优惠券的弹窗并赋予初始值
    async delayDialogVisibles(row) {
      this.delayDialogVisible = true
      this.deferDate.couponId = row.id
      this.deferDate.value4 = row.start_date
      this.deferDate.value1 = row.end_date
      console.log(row.status.id)
      if (row.status.id == -1) {
        this.disabled = false
        this.disabledT = false
      } else if (row.status.id == 0) {
        this.disabled = true
        this.disabledT = false
      } else if (row.status.id == 2) {
        this.disabled = true
        this.disabledT = false
      }
    },
    // 根据id删除对应的产品信息
    async removeProductById(row) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm(
        '是否确认删除优惠券【' + row.id + '】',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.post('admin/Coupon/delCoupon', {
        coupon_id: row.id
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getListData()
    },
    async deferCoupon() {
      var startDate = this.deferDate.value4
      var endDate = this.deferDate.value1
      var couponId = this.deferDate.couponId
      const confirmResult = await this.$confirm(
        '是否确认延期优惠券【' + couponId + '】',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消延期')
      }
      const { data: res } = await this.$http.post('admin/Coupon/deferCoupon', {
        coupon_id: couponId,
        start_date: startDate,
        end_date: endDate
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.delayDialogVisible = false
      this.getListData()
    },
    async downloadExcel() {
      this.btnLoading = true
      this.$http({
        method: 'post',
        url: '/admin/Coupon/downloadExcel',
        data: this.queryInfo.query,
        headers: {
          token: window.sessionStorage.getItem('token')
        },
        responseType: 'blob'
      })
        .then((res) => {
          this.btnLoading = false
          if (res.data.type) {
            // 文件下载
            const blob = new Blob([res.data], {
              type: 'application/vnd.ms-excel'
            })
            let link = document.createElement('a')
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', '优惠券数据.xlsx')
            link.click()
            link = null
            this.$message.success('导出成功')
          } else {
            // 返回json
            this.$message.warning(res.data.msg)
          }
        })
        .catch((err) => {
          this.btnLoading = false
          console.log(err)
          this.$message.error('下载失败')
        })
    },
    initData() {
      console.log(this.$route.query)
      if (this.$route.query.id) {
        this.queryInfo.query.id = this.$route.query.id
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-dialog__footer {
  text-align: center;
}
</style>
